package com.ljh.myaiagent.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * Prompt模板服务类
 * 负责加载和管理Prompt模板文件
 */
@Slf4j
@Service
public class PromptTemplateService {
    
    private static final String FORBIDDEN_WORD_TEMPLATE_PATH = "templates/forbidden-word-prompt.st";
    private static final String NORMAL_RESPONSE_TEMPLATE_PATH = "templates/normal-response-prompt.st";
    
    private final String forbiddenWordTemplate;
    private final String normalResponseTemplate;
    
    public PromptTemplateService() {
        this.forbiddenWordTemplate = loadTemplate(FORBIDDEN_WORD_TEMPLATE_PATH);
        this.normalResponseTemplate = loadTemplate(NORMAL_RESPONSE_TEMPLATE_PATH);
    }
    
    /**
     * 加载模板文件
     */
    private String loadTemplate(String templatePath) {
        try {
            ClassPathResource resource = new ClassPathResource(templatePath);
            return resource.getContentAsString(StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("加载模板文件失败: {}", templatePath, e);
            return getDefaultTemplate(templatePath);
        }
    }
    
    /**
     * 获取默认模板（当文件加载失败时使用）
     */
    private String getDefaultTemplate(String templatePath) {
        if (FORBIDDEN_WORD_TEMPLATE_PATH.equals(templatePath)) {
            return "抱歉，您的输入包含不当内容，请重新输入。我们致力于提供健康、积极的恋爱咨询服务。";
        } else if (NORMAL_RESPONSE_TEMPLATE_PATH.equals(templatePath)) {
            return "{systemPrompt}\n\n用户问题：{userInput}\n会话ID：{conversationId}\n时间：{timestamp}\n\n请根据以上信息提供专业的恋爱心理咨询建议。";
        }
        return "";
    }
    
    /**
     * 生成违禁词提示模板
     */
    public String generateForbiddenWordPrompt(String userInput, String forbiddenWords) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("userInput", userInput);
        variables.put("forbiddenWords", forbiddenWords);
        variables.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return replaceVariables(forbiddenWordTemplate, variables);
    }
    
    /**
     * 生成正常响应模板
     */
    public String generateNormalResponsePrompt(String systemPrompt, String userInput, String conversationId) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("systemPrompt", systemPrompt);
        variables.put("userInput", userInput);
        variables.put("conversationId", conversationId);
        variables.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        return replaceVariables(normalResponseTemplate, variables);
    }
    
    /**
     * 替换模板中的变量
     */
    private String replaceVariables(String template, Map<String, Object> variables) {
        String result = template;
        for (Map.Entry<String, Object> entry : variables.entrySet()) {
            String placeholder = "{" + entry.getKey() + "}";
            String value = entry.getValue() != null ? entry.getValue().toString() : "";
            result = result.replace(placeholder, value);
        }
        return result;
    }
}
